﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using AvansRS.Domain.DataInterface;
using StructureMap;

namespace AvansRS.Domain
{
    public class Account
    {        
        public virtual int ID { get; set; }

        [Required(ErrorMessage = ErrorMessages.UserNameRequired)]
        [CustomValidation(typeof(Account), "ValidateUsername")]
        public virtual string UserName { get; set; }

        [Required(ErrorMessage = ErrorMessages.PasswordRequired)]
        public virtual string Password { get; set; }

        [Required(ErrorMessage = "Email is verplicht.")]
        public virtual string Email { get; set; }

        public virtual string ResetKey { get; set; }

        public virtual IList<AccountRight> Rights { get; set; }

        public virtual void GenerateResetKey()
        {
            Guid guid = Guid.NewGuid();
            ResetKey = guid.ToString();
        }

		 public virtual void ResetPassword()
		 {
			 Random r = new Random();
			 Password = r.Next(100000).ToString();
		 }

        public static bool ValidateUsername(string userName, ValidationContext context, out ValidationResult result)
        {
            result = null;

            IAccountRepository repository = ObjectFactory.GetInstance<IAccountRepository>();

            Account instance = (Account) context.ObjectInstance;

            if (instance.ID > 0)
            {
                Account currentAccount = repository.GetByID(instance.ID);

                if (currentAccount.UserName == userName)
                    return true;
            }

            
            Account account = repository.FindByUsername(userName);

            if (account == null)
                return true;

            result = new ValidationResult(ErrorMessages.ExistingUserName);
            return false;
        }
    }
}
